import grace from "../../../utils/grace.js";
import {Category} from '/category-model.js';

let category = new Category();

grace.page({
    /**
     * 页面的初始数据
     */
    data: {
        categories: [],
        currentIndex: 0,
        currentId: 0,
        currentName: '',
        sub_categories: [],// 二级分类
        keywords: '',
        page: 1,
        pagesize: 20
    },
    onLoad() {
        let that = this;
        new Promise(function (resolve, reject) {
            category.getCategoryData({'token': wx.getStorageSync('token')}, (data) => {
                if (data.code == 0) {
                    that.$data.categories = data.data;
                    that.$data.currentId = data.data[0].id;
                    resolve();
                }
            }, (error) => {
                reject('error');
                console.error('error: ' + JSON.stringify(error));
            })
        }).then(function () {
            that.getSubCategories();
        })
    },
    categoryTap(e) {
        this.$data = {
            currentIndex: e.currentTarget.dataset.index,
            currentId: this.$data.categories[e.currentTarget.dataset.index].id,
            currentName: this.$data.categories[e.currentTarget.dataset.index].name,
            sub_categories: [],
            total: 0,
            page: 1,
            pagesize: 20
        }

        this.getSubCategories();
    },
    getSubCategories() {
        // 查询当前分类的二级分类
        category.getCategoryData({
            'parent_id': this.$data.currentId,
            'page': this.$data.page,
            'pagesize': this.$data.pagesize
        }, (data) => {
            if (data.code == 0) {
                this.$data.sub_categories = data.data;
            }
        })
    },
    changeKeywords(e) {
        this.$data.keywords = e.detail.value;
    },
    searchProducts() {
        if(this.$data.keywords == ''){
            wx.showToast({
                title: '请输入查询关键字',
                icon: 'loading',
            })
        }

        wx.navigateTo({
            url: '/pages/mall/product/list?keywords=' + this.$data.keywords
        })
    }
})